'use strict';
const bannerDBName = 'zhy_banner'
const jutuikeOrderDBName = 'zhy_jutuike_order'
const consumeRecordDBName = 'zhy_consume_record'
const businessInfoDBName = 'zhy_business_info'
const userInfoDBName = 'zhy_user_info'
const allowenceDBName = 'zhy_allowence_record'
const db = uniCloud.database()
const {
	doGet,
	doPost
} = require('./utils/request.js')
const sidPrefix = 'zaihuayi___'
// const config = require('./config/config.js')

/**
 * 对接jutuike聚推客联盟：
 * https://www.jutuike.com/doc/34
 */
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	if (event.syncType == 2) {
		// 聚推客联盟订单
		return await syncJutuikeOrder()
	}
	if (event.operateType == 1) {
		// 获取美团券包:http://api.jutuike.com/union/act?apikey=你的apikey&sid=123456&act_id=117
		return await getMeituanQuanbao(event)
	}
	// 根据请求参数判断调用不同的接口
	// let url = event.url
	// 默认为GET
	if (event.method != undefined && event.method != null && event.method != '' && event.method === 'POST') {
		return await doPost(event)
	} else {
		return await doGet(event)
	}
	//返回数据给客户端
	return event
};

async function getMeituanQuanbao(event) {
	if (event.user_id == null || event.user_id == undefined) {
		console.log('user_id为空');
		return 0
	}
	let param = {
		url: 'union/act',
		sid: sidPrefix + event.user_id,
		act_id: 117
	}
	let result = await doGet(param)
	console.log('result');
	console.log(JSON.stringify(result));
	/*
	{"code":1,"msg":"【success】","data":{"h5":"https://kzurl07.cn/79pB1h","long_h5":"https://p7gvdz8l.jutuike.cn/#/pages/meituan/coupon?code=P7Gvdz8L&showMenu=false","act_name":"美团券包&外卖&酒店聚合页"}} 
	*/
	/* if (result != null && result.data != null && result.data != '' && JSON.stringify(result.data) != '{}') {
		result.data.type = '1'
		// 赋值banner
		let originalMeituanQuanbaoResult = await db.collection(bannerDBName).where({
			type: '1',
		}).get()
		if (originalMeituanQuanbaoResult.data != null && originalMeituanQuanbaoResult.data.length > 0) {
			// 已存在：删除
			let updateValue = {
				h5: result.data.h5,
				long_h5: result.data.long_h5,
				act_name: result.data.act_name,
				update_time: new Date().getTime()
			}
			for (let i = 0; i < originalMeituanQuanbaoResult.data.length; i++) {
				await db.collection(bannerDBName).doc(originalMeituanQuanbaoResult.data[i]._id).update(updateValue)
			}
			console.log('修改成功！');
		} else {
			// 新增
			result.data.banner_image_url = 'banner/meituanquanbao.jpg'
			await db.collection(bannerDBName).add(result.data)
			console.log('新增完毕');
		}
		return 1
	} */
	return result.data
}

// 同步聚推客联盟订单
async function syncJutuikeOrder() {
	let list = await getALLOrdersByNowTime(new Date());
	if (list == null || list.length == 0) {
		console.log('jutuike数据为空，无需处理订单');
		return 0
	}
	// 处理订单（无需记录到消费表和订单表）：1.zhy_jutuike_order表，判断是否重复。重复则不添加 2.补贴用户（商家没有参加【平台保障计划】--不用补贴）
	for (let i = 0; i < list.length; i++) {
		let jutuikeOrder = list[i]
		// 判断order_sn是否存在
		let orderSN = jutuikeOrder.order_sn
		let exist = await orderIsExistInJutuikeOrder(orderSN)
		if (exist == null) {
			// 不存在
			// 补贴+新增
			let allowenceResult = await allowenceJutuikeOrderUser(jutuikeOrder)
			if (allowenceResult.success) {
				// 补贴成功
				jutuikeOrder.allowence_success = 1
				jutuikeOrder.allowence_consume_id = allowenceResult.allowence_consume_id
			} else {
				// 补贴失败
				jutuikeOrder.allowence_success = 0
			}
			// 新增
			await db.collection(jutuikeOrder).add(jutuikeOrder)
		} else {
			// 存在
			if (exist.allowence_success == 0) {
				// 需要再次尝试补贴
				let allowenceResult = await allowenceJutuikeOrderUser(jutuikeOrder)
				if (allowenceResult.success) {
					// 补贴成功
					jutuikeOrder.allowence_success = 1
					jutuikeOrder.allowence_consume_id = allowenceResult.allowence_consume_id
					// update
					await db.collection(jutuikeOrderDBName).doc(exist._id).update({
						allowence_success: 1,
						allowence_consume_id: allowenceResult.allowence_consume_id
					})
				} else {
					// 补贴失败
					jutuikeOrder.allowence_success = 0
					// 不需要修改
				}
			}
		}
		// 睡眠，反正服务器压力大
		await sleep(500)
	}
	return 1
}

// 根据第三方补贴用户
async function allowenceJutuikeOrderUser(jutuikeOrder) {
	let result = {
		allowence_success: 0,
		allowence_consume_id: ''
	}
	if (objIsEmpty(jutuikeOrder)) {
		console.log('错误：订单为空');
		console.log(JSON.stringify(jutuikeOrder));
		return result
	}
	// 1.解析出用户
	let user_id = resolveSid(jutuikeOrder.sid)
	if (objIsEmpty(user_id)) {
		console.log('订单sid解析失败【sid格式错误】：', JSON.stringify(jutuikeOrder));
		return result
	}
	// 2.查询用户是否存在门店消费 且 该商家参与了【平台保障计划】，没有就返回null
	let allowencingConsume = await getUserAllowencingComsume(user_id) // 消费对象：consume_record
	if (allowencingConsume == null) {
		// 没有补贴中且参与了平台保障计划的消费记录
		console.log('没有补贴中且参与了平台保障计划的消费记录,user_id:' + user_id);
		return result
	}
	// 补贴：在花币增加，红包减少
	// 返回补贴金额allowenceAmount，单位：分.补贴失败返回null
	let r = await userAllowence(user_id, allowencingConsume, jutuikeOrder.jtk_share_fee);
	if (!r.allowenceSuccess) {
		// 失败
		console.log('补贴失败');
		return result
	}
	// 成功
	result.allowence_consume_id = allowencingConsume._id
	result.allowence_success = 1
	result.allowence_amount = r.allowenceAmount // 补贴金额：应该为佣金，但是有可能红包不够减--怕超过最大红包数量
	return result
}

// 补贴用户：在花币+  红包- ，补贴记录，可能修改消费记录状态
async function userAllowence(user_id, allowencingConsume, jtk_share_fee) {
	// 判断补贴金额
	let result = {
		// allowenceAmount: jtk_share_fee_fen,
		consumeisFinished: false,
		allowenceSuccess: false
	}
	if (objIsEmpty(user_id) || objIsEmpty(jtk_share_fee)) {
		console.log('参数不齐');
		console.log('user_id:' + user_id);
		console.log('jtk_share_fee:' + jtk_share_fee);
		return result
	}
	let jtk_share_fee_fen = regYuanToFen(jtk_share_fee, 100)
	result.allowenceAmount = jtk_share_fee_fen

	// 1.用户红包是否充足
	let userInfo = await getUserInfo(user_id)
	if (userInfo == null) {
		console.log('用户不存在');
		return null
	}
	// 获取用户已补贴金额
	let allowencedTotal = await getUserTotalAllowencedAmount(user_id, allowencingConsume._id)
	let leftMaxAllowenceAmount = allowencingConsume.max_allowence_amount
	if (userInfo.red_wallet > leftMaxAllowenceAmount) {
		// 红包剩余更多，比较 剩余的补贴金和佣金大小
		if (leftMaxAllowenceAmount > jtk_share_fee_fen) {
			// 补贴 佣金jtk_share_fee_fen
			result.allowenceAmount = jtk_share_fee_fen
		} else {
			// 补贴 leftMaxAllowenceAmount，设置是否补贴结束，修改消费记录状态
			result.allowenceAmount = leftMaxAllowenceAmount
			result.consumeisFinished = true
		}
	} else {
		// 红包更少，比较 红包和佣金大小
		if (userInfo.red_wallet > jtk_share_fee_fen) {
			// 正常补贴：jtk_share_fee_fen
			result.allowenceAmount = jtk_share_fee_fen
		} else {
			// 补贴 佣金userInfo.red_wallet
			// 照理说不能走到这一步的
			result.allowenceAmount = userInfo.red_wallet
		}
	}
	// 开始补贴:新增补贴记录，修改用户（在花币和红包），可能会修改消费记录状态
	let allowenceAddParam = {
		user_id: user_id,
		business_id: allowencingConsume.business_id,
		consume_id: allowencingConsume_id,
		bs_reverse_allowence_amount: 0,
		zhb_allowence_amount: result.allowenceAmount,
		allowence_time: new Date().getTime()
	}
	await db.collection(allowenceDBName).add(allowenceAddParam)
	// 修改用户在花币和红包
	await updateUserZHBAndRedWallet(userInfo, result.allowenceAmount)
	// 判断是否结束：修改消费状态-已完成
	if (result.consumeisFinished) {
		await updateConsumeFinished(allowencingConsume._id)
	}
}

// 修改消费状态-已完成
async function updateConsumeFinished(consume_id) {
	if (objIsEmpty(consume_id)) {
		return 0
	}
	await db.collection(consumeRecordDBName).doc(consume_id).update({
		consume_status: 2
	})
	return 1
}

// 修改用户在花币和红包
async function updateUserZHBAndRedWallet(userInfo, allowenceAmount) {
	if (objIsEmpty(userInfo) || objIsEmpty(allowenceAmount)) {
		console.log('参数不齐');
		return 0
	}
	let red = userInfo.red_wallet - allowenceAmount
	let zhb = userInfo.zhb_num + allowenceAmount
	await db.collection(userInfoDBName).doc(userInfo._id).update({
		red_wallet: red,
		zhb_num: zhb
	})
	return 1
}

// 获取用户已补贴商家的金额
async function getUserTotalAllowencedAmount(user_id, consume_id) {

}

// 获取用户正在补贴中的消费记录（随机）
async function getUserAllowencingComsume(user_id) {
	if (objIsEmpty(user_id)) {
		return null
	}
	let res = await db.collection(consumeRecordDBName).where({
		user_id: user_id,
		consume_status: 1
	}).get()
	if (res == null || res.data == null || res.data.length == 0) {
		return null
	}
	let arr = res.data;
	let joinJihua = []
	// 判断补贴的商家是否参与了 平台保证计划
	for (let i = 0; i < arr.length; i++) {
		let consumeR = arr[i]
		let isJoin = await businessJoinJihua(consumeR.business_id)
		if (isJoin) {
			// 参与了
			joinJihua.push(consumeR)
		} else {
			// 未参与
			console.log('商家未参与平台保证计划,business_id:' + consumeR.business_id);
		}
	}
	if (joinJihua.length == 0) {
		console.log('无满足条件的商家');
		return null
	}
	// 随机选择一个
	let rand = Math.floor(Math.random() * joinJihua.length);
	let rValue = joinJihua[rand];
	return rValue
}

// 判断business_id是否参加了平台保障计划
async function businessJoinJihua(business_id) {
	if (objIsEmpty(business_id)) {
		return false
	}
	let res = await db.collection(businessInfoDBName).where({
		offlineBusinessId: business_id,
		join_platform_guarantee_plan: 1
	}).get()
	if (res == null || res.data == null || res.data.length == 0) {
		return false
	}
	return true
}

// 解析sid，返回user_id(zaihuayi___+user_id)
function resolveSid(sid) {
	if (objIsEmpty(sid)) {
		console.log('sid为空', sid);
		return null
	}
	return sid.replace('zaihuayi___', '')
}

// 根据现在时间获取前一小时的订单
async function getALLOrdersByNowTime(date) {
	let resultList = []
	let pageSize = 100;
	let page = 1
	while (true) {
		let param = {
			url: 'union/orders',
			start_time: getFormatDate(getHoursBefore(date, 1)),
			end_time: getFormatDate(date),
			status: 3, //只要已结算成功的。订单统一状态，0：未付款 1：已付款 2：待结算 3：已结算 4：无效订单
			page: page,
			pageSize: pageSize, //每页显示多少 默认 20 最大 100
		}
		let pageResult = await doGet(param)
		/*
		{
		    "code": 0,
		    "msg": "【对应条件内无数据】",
		    "data": []
		}
		*/
		if (pageResult == null || pageResult == undefined || pageResult.data == null ||
			pageResult.data.length == 0) {
			console.log('无数据');
			return resultList
		}
		let orderList = pageResult.data;
		if (orderList.length < pageSize) {
			// 查询完毕
			resultList.concat(orderList)
			break
		} else {
			// 继续查询
			page = page + 1
		}
	}
	return resultList
}

//获取当前日期函数
function getFormatDate(date) {
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentDate = date.getFullYear() + "-" + month + "-" + strDate +
		" " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
	return currentDate;
}

// 获取当前时间前几个小时的日期
function getHoursBefore(date, n) {
	return new Date(date.getTime() - n * 60 * 60 * 1000)
}

// 聚推客订单是否存在于jutuikeOrderDBName。存在则返回对象，不存在返回null
async function orderIsExistInJutuikeOrder(orderSN) {
	if (objIsEmpty(orderSN)) {
		return null
	}
	let order = await db.collection(jutuikeOrderDBName).where({
		order_sn: orderSN
	}).limit(1).get()
	if (order != null && order.data != null && order.data.length > 0) {
		return order.data[0]
	}
	return null
}

// 判断对象是否为空
function objIsEmpty(obj) {
	if (obj == null || obj == undefined || obj == '' || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}

// 睡眠，单位毫秒
function sleep(delay) {
	return new Promise((resolve) => setTimeout(resolve, delay));
}

function regYuanToFen(yuan, digit) {
	let m = 0
	let s1 = yuan.toString()
	let s2 = digit.toString()
	try {
		m += s1.split('.')[1].length
	} catch (e) {}
	try {
		m += s2.split('.')[1].length
	} catch (e) {}
	return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

// 用户用户信息
async function getUserInfo(user_id) {
	let res = await db.collection(userInfoDBName).where({
		user_id: user_id
	}).get()
	if (res == null || res.data == null || res.data.length == 0) {
		return null
	}
	return res.data[0]
}